import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { Role } from './entities/role.entity';
import { IsNull, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { SelectRoleDTO } from './dto/select-role.dto';
import { RoleMenuService } from '../role-menu/role-menu.service';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role)
    private readonly roleRepostiory: Repository<Role>,
    private readonly roleMenuService: RoleMenuService
  ) {}
  // 创建角色
  async create(createRoleDto: CreateRoleDto) {
    try {
      const menu_ids = createRoleDto.menu_ids
      delete createRoleDto.role_id
      delete createRoleDto.menu_ids
      const result = await this.roleRepostiory.insert(createRoleDto)
      menu_ids.forEach(async (menu_id) => {
        await this.roleMenuService.create({ role_id: result.generatedMaps[0].role_id , menu_id: menu_id})
      });
      delete result.generatedMaps[0].del_time
      return result.generatedMaps[0]
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 获取所有角色
  async findAll(data: SelectRoleDTO) {
    try {
      const skip: number = (data.pageIndex-1) * data.pageSize;
      const take: number = data.pageSize;
      const q =  this.roleRepostiory.createQueryBuilder('r')
      .where({ del_time: IsNull()})
      .skip(skip)
      .take(take)
      .orderBy('r.role_sort', 'ASC')
      for (const key of Object.keys(new SelectRoleDTO())) {
        if(key === 'pageIndex' || key === 'pageSize') continue;
        if (data[key]) {
          const where = {}
          where[key] = data[key]
          q.andWhere(where)
        }
      }
      const result = await q.getMany()
      const total = await this.roleRepostiory.count()
      return {
        list: result,
        page: data.pageIndex, // 当前页码
        pageSize: result.length, // 查询条数
        next: data.pageIndex * data.pageSize < total, // 是否有下一页
        total: total, // 共多少条
      }
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 根据角色id查询角色信息
  async findOne(id: number) {
    try {
      const result = await this.roleRepostiory.findOne({
        where: {
          del_time: IsNull(),
          role_id: id
        }
      })
      return result
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

   // 修改角色信息
  async update(id: number, updateRoleDto: UpdateRoleDto) {
    try {
      const menu_ids = updateRoleDto.menu_ids
      delete updateRoleDto.menu_ids
      const result = await this.roleRepostiory.update(id, updateRoleDto)
      await this.roleMenuService.update(id, menu_ids)
      return result.affected == 1
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  // 删除角色
  remove(id: number) {
    try {
      return this.roleRepostiory.createQueryBuilder()
      .update()
      .set({ del_time: Date.now() })
      .where({ role_id: id })
      .execute()
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR)
    }
    
  }
}
